package com.nineclock.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nineclock.attendance.dto.DepartmentOrUserSimpleDTO;
import com.nineclock.common.entity.PageResult;
import com.nineclock.common.entity.Result;
import com.nineclock.common.entity.UserInfo;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.common.threadlocal.CurrentUserHolder;
import com.nineclock.common.utils.BeanHelper;
import com.nineclock.system.dto.SysCompanyUserDTO;
import com.nineclock.system.dto.SysDepartmentDTO;
import com.nineclock.system.mapper.SysCompanyUserMapper;
import com.nineclock.system.mapper.SysDepartmentMapper;
import com.nineclock.system.pojo.SysCompanyUser;
import com.nineclock.system.pojo.SysDepartment;
import com.nineclock.system.service.OrganizationService;
import com.nineclock.system.service.SysCompanyUserService;
import io.jsonwebtoken.lang.Collections;
import lombok.extern.slf4j.Slf4j;
import org.omg.CORBA.CurrentHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrganizationServiceImpl implements OrganizationService {
    @Override
    public List<Long> queryDepartmentsByUserId(Long companyUserId) {
        List<Long> ids = new ArrayList<>();

        if(companyUserId == null){
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }
        //根据员工id 查询员工信息
        SysCompanyUser companyUser = sysCompanyUserMapper.selectById(companyUserId);
        if(companyUser == null){
            throw new NcException(ResponseEnum.USER_NOT_FOUND);
        }

        //获取员工所在的部门
        Long departmentId = companyUser.getDepartmentId();
        ids.add(departmentId);
        // 获取部门所在的上级部门id
        while (true){
            //根据部门id查询部门信息
            SysDepartment department = sysDepartmentMapper.selectById(departmentId);
            //获取部门的上级部门id
            Long parentId = department.getParentId();
            //如果查询到顶级部门，则退出
            if(parentId == 0){
                break;
            }
            //上级部门id添加到集合中
            ids.add(parentId);
            //为下一次循环做准备， 根据上级部门id查询上级部门
            departmentId = parentId;
        }

        return ids;
    }
    @Autowired
    SysCompanyUserMapper sysCompanyUserMapper;
    @Autowired
    SysCompanyUserService sysCompanyUserService;

    @Override
    public List<SysCompanyUserDTO> getCompanyUserList() {
        List<SysCompanyUserDTO> ls = sysCompanyUserService.getCompanyUserList();
        return ls;
    }

    /**
     * 返回部门层级列表
     *
     * @return
     */
    @Override
    public List<SysDepartmentDTO> getCompanyDepartmentList() {
        Long companyId = CurrentUserHolder.get().getCompanyId();
        ArrayList<SysDepartmentDTO> sys = new ArrayList<>();
        List<SysDepartmentDTO> theDepartment = getTheDepartment(0, companyId, sys);
        return theDepartment;
    }

    @Override
    public PageResult<SysCompanyUserDTO> getCompanyDepartmentUserList(Integer page, Integer pageSize, String keyword, Long departmentId) {
        Page<SysCompanyUser> companyUserPage = new Page<>(page,pageSize);
        Long companyId = CurrentUserHolder.get().getCompanyId();
        LambdaQueryWrapper<SysCompanyUser> s = new LambdaQueryWrapper<>();
        s.eq(SysCompanyUser::getCompanyId,companyId);
        if (departmentId!=0) {
            List<Long> list=new ArrayList<>();
            list.add(departmentId);
            getAllDownDepartmentList(departmentId,companyId,list);
            s.in(SysCompanyUser::getDepartmentId,list);
        }
        if (keyword!=null&&keyword.length()!=0) {
            s.and(s1 ->{
                s1.like(SysCompanyUser::getUserName,keyword)
                        .or().like(SysCompanyUser::getWorkNumber,keyword)
                        .or().like(SysCompanyUser::getMobile,keyword);
            });
        }
        companyUserPage = sysCompanyUserMapper.selectPage(companyUserPage,s);
        if (companyUserPage!=null) {
            PageResult<SysCompanyUserDTO> sysCompanyUserPageResult = new PageResult<>();
            List<SysCompanyUserDTO> sysCompanyUsers = BeanHelper.copyWithCollection(companyUserPage.getRecords(), SysCompanyUserDTO.class);
            sysCompanyUserPageResult.setRows(sysCompanyUsers);
            sysCompanyUserPageResult.setTotalPage(companyUserPage.getPages());
            sysCompanyUserPageResult.setTotal(companyUserPage.getTotal());
            return sysCompanyUserPageResult;
        }

        return new PageResult<SysCompanyUserDTO>();
    }

    @Override
    public List<Long> queryTopDepartmentIds() {

        LambdaQueryWrapper<SysDepartment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysDepartment::getCompanyId, CurrentUserHolder.get().getCompanyId());
        wrapper.eq(SysDepartment::getParentId, 0); //顶级部门

        List<SysDepartment> departmentList = sysDepartmentMapper.selectList(wrapper);
        if(CollectionUtil.isNotEmpty(departmentList)){
            List<Long> ids = departmentList.stream().map(department -> {
                return department.getId();
            }).collect(Collectors.toList());
            return ids;
        }
        return new ArrayList<>();
    }

    @Override
    public List<DepartmentOrUserSimpleDTO> querySimpleDepartment(Long departmentId, Integer includeMember) {
        List<DepartmentOrUserSimpleDTO> all = new ArrayList<>();

        // 查询departmentId 子部门
        LambdaQueryWrapper<SysDepartment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysDepartment::getParentId, departmentId);
        wrapper.eq(SysDepartment::getCompanyId,CurrentUserHolder.get().getCompanyId());
        List<SysDepartment> departmentList = sysDepartmentMapper.selectList(wrapper);
        //把 部门列表转换为 返回值类型列表
        List<DepartmentOrUserSimpleDTO> departmentSimpleList = departmentList.stream().map(department -> {
            DepartmentOrUserSimpleDTO departmentSimpleDTO = new DepartmentOrUserSimpleDTO();
            departmentSimpleDTO.setType(1);
            departmentSimpleDTO.setId(department.getId());
            departmentSimpleDTO.setName(department.getName());
            return departmentSimpleDTO;
        }).collect(Collectors.toList());

        all.addAll(departmentSimpleList);

        //如果 includeMember为0 ，说明包含员工信息
        if( includeMember == 0){
            LambdaQueryWrapper<SysCompanyUser> companyUserQw = new LambdaQueryWrapper<>();
            companyUserQw.eq(SysCompanyUser::getCompanyId, CurrentUserHolder.get().getCompanyId());
            companyUserQw.eq(SysCompanyUser::getDepartmentId, departmentId);
            List<SysCompanyUser> companyUserList = sysCompanyUserMapper.selectList(companyUserQw);

            List<DepartmentOrUserSimpleDTO> userSimpleDTOList = companyUserList.stream().map(companyUser -> {
                DepartmentOrUserSimpleDTO userSimpleDTO = new DepartmentOrUserSimpleDTO();
                userSimpleDTO.setType(2);
                userSimpleDTO.setName(companyUser.getUserName());
                userSimpleDTO.setId(companyUser.getId());
                return userSimpleDTO;
            }).collect(Collectors.toList());

            all.addAll(userSimpleDTOList);
        }

        return all;
    }

    /**
     * 获得下属部门ids
     * @param departmentId
     * @param companyId
     * @param list
     * @return
     */
    public List<Long> getAllDownDepartmentList(Long departmentId, Long companyId, List<Long> list) {
        LambdaQueryWrapper<SysDepartment> s = new LambdaQueryWrapper<>();
        s.eq(SysDepartment::getParentId,departmentId);
        s.eq(SysDepartment::getCompanyId,companyId);
        List<SysDepartment> sysDepartments = sysDepartmentMapper.selectList(s);
        if (Collections.isEmpty(sysDepartments)) {
            return null;
        }
        for (SysDepartment sysDepartment : sysDepartments) {
            Long id = sysDepartment.getId();
            List<Long> allDownDepartmentList = getAllDownDepartmentList(id, companyId, list);
            if (Collections.isEmpty(allDownDepartmentList)) {
                list.add(id);
            }
        }
        return list;
    }


    /**
     * 查询该id,companyid下部门
     */
    @Autowired
    SysDepartmentMapper sysDepartmentMapper;

    public List<SysDepartmentDTO> getTheDepartment(long id, long companyId, List<SysDepartmentDTO> list) {
        LambdaQueryWrapper<SysDepartment> s = new LambdaQueryWrapper<>();
        s.eq(SysDepartment::getCompanyId, companyId);
        s.eq(SysDepartment::getParentId, id);
        List<SysDepartment> sysDepartments = sysDepartmentMapper.selectList(s);
        if (Collections.isEmpty(sysDepartments)) {
            return null;
        }
        for (SysDepartment sysDepartment : sysDepartments) {
            SysDepartmentDTO sysDepartmentDTO = BeanHelper.copyProperties(sysDepartment, SysDepartmentDTO.class);
            List<SysDepartmentDTO> theDepartment = getTheDepartment(sysDepartment.getId(), companyId, new ArrayList<SysDepartmentDTO>());
            if (!Collections.isEmpty(theDepartment)) {
                sysDepartmentDTO.setChildren(theDepartment);
            }list.add(sysDepartmentDTO);
        }return list;
    }
}